﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using Microsoft.Linq.Expressions;

namespace DlrBasic.Parser
{
    class FunctionScope
    {
        string name;

        public string Name
        {
            get { return name; }
        }

        LambdaBuilder builder;
        Dictionary<string, Expression> parameters;

        public FunctionScope(Type returnType, string name, FunctionParameter[] parameterNames)
        {
            this.name = name;
            builder = Utils.Lambda(returnType, name);
            parameters = new Dictionary<string, Expression>(StringComparer.InvariantCultureIgnoreCase);
            for (int i = 0; i < parameterNames.Length; i++)
            {
                parameters.Add(parameterNames[i].Name, 
                    builder.Parameter(parameterNames[i].Type, parameterNames[i].Name));
            }
        }

        public bool IsParameterPresent(string name)
        {
            return parameters.ContainsKey(name);
        }

        public Expression GetParameter(string name)
        {
            return parameters[name];
        }

        public void SetBody(Expression expression)
        {
            builder.Body = expression;
        }

        public LambdaExpression ToLambdaExpression()
        {
            return builder.MakeLambda();
        }
    }

    struct FunctionParameter
    {
        public string Name;
        public Type Type;

        public FunctionParameter(string name, Type type)
        {
            Name = name;
            Type = type;
        }
    }
}
